﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using System;
using LeanCloud;
using LeanCloud.Storage;

public class LoginPanel : UIBase
{
    private static string path = "UI/LoginPanel";
    private static UILayer layer = UILayer.Mid;
    private readonly string loginTitle = "登录", registerTitle = "注册";
    private readonly string submitTitle = "确认", cancleTitle = "取消";

    private Text title;
    private Transform submitBtn, registerBtn;
    private InputField playerNameInput, playerPasswordInput;
    private string playerName, playerPassword;

    protected override void Awake()
    {
        base.Awake();
        #region 进入动画
        float startY = Screen.height / 2f + GetComponent<RectTransform>().sizeDelta.y / 2f;
        transform.localPosition = new Vector3(0, startY, 0);
        transform.DOLocalMoveY(0, 0.5f).SetEase(Ease.OutBack);
        #endregion
        #region 找到相关物体
        submitBtn = transform.Find("SubmitBtn");
        registerBtn = transform.Find("RegisterBtn");
        title = transform.Find("Title").GetComponent<Text>();
        playerNameInput = transform.Find("PlayerNameInput").GetComponent<InputField>();
        playerPasswordInput = transform.Find("PlayerPasswordInput").GetComponent<InputField>();
        #endregion
    }

    public override void Open(params System.Object[] parameters)
    {
        EnterLoginPanel();
        CheckLocalUser();
    }

    public override void Close()
    {
        DestroyImmediate(this.gameObject);
    }

    #region 两个按钮的四个功能
    private void LoginClick()
    {
        GetInputContent();
        if (string.IsNullOrEmpty(playerName))
        {
            UIMgr.Instance.ShowTipLabel("玩家名不能为空");
            return;
        }
        if (string.IsNullOrEmpty(playerPassword))
        {
            UIMgr.Instance.ShowTipLabel("密码不能为空");
            return;
        }
        LoginRequest(playerName,playerPassword);
    }

    private void RegisterClick()
    {
        EnterRegisterPanel();
    }

    private void SubmitClick()
    {
        GetInputContent();
        if (string.IsNullOrEmpty(playerName))
        {
            UIMgr.Instance.ShowTipLabel("玩家名不能为空");
            return;
        }
        if (string.IsNullOrEmpty(playerPassword))
        {
            UIMgr.Instance.ShowTipLabel("密码不能为空");
            return;
        }
        RegisterRequest(playerName, playerPassword);
    }

    private void CancleClick()
    {
        EnterLoginPanel();
    }
    #endregion

    /// <summary>
    /// 进入登录界面
    /// </summary>
    private void EnterLoginPanel()
    {
        title.text = loginTitle;
        submitBtn.GetComponentInChildren<Text>().text = loginTitle;
        submitBtn.GetComponent<Button>().AddClickListener(LoginClick);
        registerBtn.GetComponentInChildren<Text>().text = registerTitle;
        registerBtn.GetComponent<Button>().AddClickListener(RegisterClick);
        ClearInput();
    }

    /// <summary>
    /// 进入注册界面
    /// </summary>
    private void EnterRegisterPanel()
    {
        title.text = registerTitle;
        submitBtn.GetComponentInChildren<Text>().text = submitTitle;
        submitBtn.GetComponent<Button>().AddClickListener(SubmitClick);
        registerBtn.GetComponentInChildren<Text>().text = cancleTitle;
        registerBtn.GetComponent<Button>().AddClickListener(CancleClick);
        ClearInput();
    }

    /// <summary>
    /// 清空输入框中的内容
    /// </summary>
    private void ClearInput()
    {
        playerNameInput.text = string.Empty;
        playerPasswordInput.text = string.Empty;
    }

    private void CheckLocalUser()
    {
        if (DataMgr.Instance.HavePlayerCache())
        {
            playerNameInput.text = DataMgr.Instance.Player.userName;
            playerPasswordInput.text = DataMgr.Instance.Player.userPassword;
        }
    }

    /// <summary>
    /// 获取输入框中的内容
    /// </summary>
    private void GetInputContent()
    {
        playerName = playerNameInput.text;
        playerPassword = playerPasswordInput.text;
    }

    private async void LoginRequest(string name, string password)
    {
        bool isSuccess = true;
        LCUser user = null;
        try{
            user = await LCUser.Login(name, password);
        }
        catch (LCException e){
            string showLabel = string.Empty;
            if (e.Code == 210)
            {
                showLabel = "密码错误";
            }
            else if (e.Code == 211)
            {
                showLabel = "玩家不存在";
            }
            isSuccess = false;
            UIMgr.Instance.ShowTipLabel(showLabel);
        }
        if (isSuccess)
        {
            Networker.Instance.User = user;
            DataMgr.Instance.Player = new User(name, password);
            EventDispatcher.Login_Dispatch();
            Close();
        }
    }

    private async void RegisterRequest(string name,string password)
    {
        LCUser user = new LCUser();
        user.Username = name;
        user.Password = password;
        bool isSuccess = true;
        try
        {
            await user.SignUp();
        }
        catch(LCException e)
        {
            isSuccess = false;
            if (e.Code==202)
            {
                UIMgr.Instance.ShowTipLabel("玩家名已存在");
            }
        }
        if (isSuccess)
        {
            UIMgr.Instance.ShowTipLabel("创建成功");
            EnterLoginPanel();
        }
    }
}
